package com.myblog.service;

import com.myblog.Mapper.CommentMapper;
import com.myblog.po.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentMapper commentService;

    @Override
    public List<Comment> listCommentByBlogId(Long id) {

        List<Comment> comments = commentService.findByBlogIdAndParentComment(id);
        for (Comment c : comments){
            c.setReplyComments(commentService.findByBlogIdAndReplyComment(c.getId()));
        }

    //    List<Comment>comments =  commentRepository.findByBlogIdAndParentCommentNull(blogId, Sort.by(Sort.Direction.DESC,"createTime"));

        return eachComment(comments);
    }

    @Override
    public void saveComment(Comment comment) {

        commentService.saveComment(comment);
    }


    private  List<Comment> tempReplys = new ArrayList<>();




    private  List<Comment> eachComment(List<Comment> comments){
        List<Comment> commentsView = new ArrayList<>();
        for(Comment comment:comments){
            Comment c = new Comment();
            BeanUtils.copyProperties(comment,c);
            commentsView.add(c);
        }
        /**/
        combineChildren(commentsView);
        return commentsView;
    }


    private void combineChildren(List<Comment> comments){

        for(Comment comment :comments){
            List<Comment> replys1 = comment.getReplyComments();
            for(Comment reply1:replys1){

                /**/
                recursively(reply1);
            }

            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();

        }

    }



    private void recursively(Comment comment){
        tempReplys.add(comment);
        if(comment.getReplyComments().size()>0){
            List<Comment> replys = comment.getReplyComments();
            for(Comment reply:replys){
                tempReplys.add(reply);
                if(reply.getReplyComments().size()>0){
                    recursively(reply);
                }
            }
        }

    }

}
